using Microsoft.AspNetCore.Mvc;
using ZZ_ICU.Models;
using System.Linq;
using ZZ_ICU.Services.Interfaces;

namespace ZZ_ICU.Controllers
{
    public class PatientsController : Controller
    {
        private readonly IPatientService _patientService;

        public PatientsController(IPatientService patientService)
        {
            _patientService = patientService;
        }

        // 验证用户是否已登录，未登录则重定向到登录页面
        private bool CheckLogin()
        {
            var userId = HttpContext.Session.GetString("UserId");
            return !string.IsNullOrEmpty(userId);
        }

        // GET: /Patients
        public async Task<IActionResult> Index(bool mine = false, bool showEmpty = false, string? selectedBed = null)
        {
            if (!CheckLogin())
            {
                return RedirectToAction("Index", "Login");
            }

            var currentNurse = HttpContext.Session.GetString("UserName") ?? string.Empty;
            var vm = await _patientService.GetDashboardAsync(currentNurse, mine, showEmpty, selectedBed);
            return View(vm);
        }

        // GET: /Patients/Accept  接收病人（占位页）
        public IActionResult Accept()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // GET: /Patients/EmergencyIn  紧急入科（占位页）
        public IActionResult EmergencyIn()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 出科管理（占位）
        public IActionResult Discharge()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 修改病人信息（占位）
        public IActionResult Edit()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 床位管理
        public IActionResult BedManagement()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 计算年龄
        private int CalculateAge(DateTime birthDate, DateTime currentDate)
        {
            var age = currentDate.Year - birthDate.Year;
            if (birthDate.Date > currentDate.AddYears(-age)) age--;
            return age;
        }

        // 医嘱（占位）
        public IActionResult Orders()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 检验数据分析（占位）
        public IActionResult LabAnalysis()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 患者信息页面
        public IActionResult PatientInfo()
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            return View();
        }

        // 患者详情页面
        public IActionResult PatientDetail(string? bedNo = null)
        {
            if (!CheckLogin()) return RedirectToAction("Index", "Login");
            // 可以在这里根据bedNo获取患者数据并传递给视图
            // 目前先直接返回视图，前端会通过JavaScript获取数据
            return View();
        }

        // AJAX: 获取患者详细信息
        [HttpGet]
        public async Task<IActionResult> GetPatientDetail(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            if (string.IsNullOrEmpty(bedNo)) return BadRequest();

            var currentNurse = HttpContext.Session.GetString("UserName") ?? string.Empty;
            var vm = await _patientService.GetDashboardAsync(currentNurse, false, false, bedNo);

            if (vm?.SelectedPatient == null)
                return NotFound();

            return Json(new
            {
                success = true,
                data = vm.SelectedPatient
            });
        }

        // ========== 动态加载局部视图的 Action 方法 ==========

        // 加载首页内容
        [HttpGet]
        public IActionResult LoadHome(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_HomeContent");
        }

        // 加载监护数据
        [HttpGet]
        public IActionResult LoadMonitorData(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_MonitorDataContent");
        }

        // 加载皮肤信息
        [HttpGet]
        public IActionResult LoadSkin(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_SkinContent");
        }

        // 加载导管信息
        [HttpGet]
        public IActionResult LoadCatheter(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_CatheterContent");
        }

        // 加载护理记录单
        [HttpGet]
        public IActionResult LoadNursingRecord(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_NursingRecordContent");
        }

        // 加载护理文书
        [HttpGet]
        public IActionResult LoadNursingDocument(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_NursingDocumentContent");
        }

        // 加载体温单
        [HttpGet]
        public IActionResult LoadTemperature(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_TemperatureContent");
        }

        // 加载重症评分
        [HttpGet]
        public IActionResult LoadCriticalScore(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_CriticalScoreContent");
        }

        // 加载预警信息
        [HttpGet]
        public IActionResult LoadWarningInfo(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_WarningInfoContent");
        }

        // 加载收费单明细
        [HttpGet]
        public IActionResult LoadBillingDetail(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_BillingDetailContent");
        }

        // 加载每日质控
        [HttpGet]
        public IActionResult LoadDailyQualityControl(string bedNo)
        {
            if (!CheckLogin()) return Unauthorized();
            ViewBag.BedNo = bedNo;
            return PartialView("_DailyQualityControlContent");
        }
    }
}


